<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { getBarChart } from '@/api/index'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    typeName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    typeName(newVal, oldVal) {
      this.initChart()
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      var title = ''
      var top = ''

      const query = { type_name: this.typeName }
      getBarChart(query).then(response => {
        var source = [[]]
        if (response.source) {
          source = response.source
          title = response.title
        }
        if (response.message) {
          title = response.message
          top = 'center'
        }
        this.chart.setOption({
          title: {
            // show: showed, // 是否显示title
            text: title,
            top: top,
            left: 'center',
            textStyle: {
              color: 'black',
              fontSize: 20,
              fontWeight: 400
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
              type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
          },
          grid: {
            left: '2%',
            right: '2%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [{
            type: 'category'
          }],
          yAxis: [{
            type: 'value',
            axisTick: {
              show: false
            }
          }],
          dataset: [{
            source: source
          }],
          series: [
            {
              type: 'bar',
              barMaxWidth: 40,
              label: {
                show: true,
                position: 'top',
                textStyle: {
                  color: 'black'
                }
              }
            }
          ]
        })
      })
    }
  }
}
</script>
